package com.xinqi.common.third.mail.help;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * @author linkai
 * @date 2023/2/21
 */
@Slf4j
@RequiredArgsConstructor
public class MailHelp {
    private final JavaMailSender javaMailSender;
    private final String defaultFrom;

    /**
     * 发送邮件
     *
     * @param to      收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void send(String to, String subject, String content) {
        sendAttachMail(defaultFrom, to, null, subject, content, null);
    }

    /**
     * 发送邮件
     *
     * @param from    邮件发送者
     * @param to      收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void send(String from, String to, String subject, String content) {
        sendAttachMail(from, to, null, subject, content, null);
    }

    /**
     * 发送邮件
     *
     * @param from    邮件发送者
     * @param to      收件人
     * @param cc      抄送人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String from, String to, String cc, String subject, String content) {
        try {
            // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
            SimpleMailMessage simpMsg = new SimpleMailMessage();
            simpMsg.setFrom(from);
            simpMsg.setTo(to);
            if (StringUtils.isNotBlank(cc)) {
                simpMsg.setCc(cc);
            }
            simpMsg.setSubject(subject);
            simpMsg.setText(content);
            javaMailSender.send(simpMsg);
        } catch (MailException e) {
            log.error("普通邮件发送异常，form = {}, to = {}", from, to, e);
            throw e;
        } catch (Exception e) {
            log.error("普通邮件发送错误，form = {}, to = {}", from, to, e);
            throw new MailSendException("邮件发送失败", e);
        }
    }

    /**
     * 发送邮件（带附件）
     *
     * @param from    邮件发送者
     * @param to      收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param files   附件列表
     */
    @SuppressWarnings("DuplicatedCode")
    public void sendAttachMail(String from, String to, String cc, String subject, String content, List<File> files) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            // 这里使用 MimeMessageHelper 简化了邮件配置
            // 第二个参数true表示构造一个 multipart message 类型邮件
            // multipart message类型邮件包含多个正文、附件以及内嵌资源，邮件表现形式更加丰富
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            if (StringUtils.isNotBlank(cc)) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            helper.setText(content, true);
            if (CollectionUtils.isNotEmpty(files)) {
                for (File file : files) {
                    helper.addAttachment(file.getName(), file);
                }
            }
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.error("邮件【带附件】发送异常，form = {}, to = {}", from, to, e);
            throw new MailSendException("邮件发送失败", e);
        }
    }

    /**
     * @param from
     * @param to
     * @param subject
     * @param content 内容
     * @param srcPath 资源路劲
     * @param resIds  资源ID
     */
    @SuppressWarnings("DuplicatedCode")
    public void sendResMail(String from, String to, String cc, String subject, String content,
                            String[] srcPath, String[] resIds) {
        if (ArrayUtils.isEmpty(srcPath)) {
            log.error("邮件【静态资源】发送异常，没有静态资源！form = {}, to = {}", from, to);
            return;
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            if (StringUtils.isNotBlank(cc)) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            // 第二个参数true表示邮件正文是HTML格式（默认为false）
            helper.setText(content, true);
            for (int i = 0; i < srcPath.length; i++) {
                // 通过FileSystemResource构造静态资源，让后调用addInline方法将资源加入到邮件对象中
                FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
                helper.addInline(resIds[i], res);
            }
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.error("邮件【静态资源】发送异常，form = {}, to = {}", from, to, e);
            throw new MailSendException("邮件发送失败", e);
        }
    }
}
